<?php

/******************************************************
* 操作数据库
* CURD操作类
*/

class Db
{
	/**
	* 设置数据库配置
	*/
	private $user = 'root';
	private $pass = 'Aa123123';
	private $host = '154.209.4.135';
	private $db   = 'qianqiuxs';
	
	// 连接数据库
	private $conn = '';

	/********************************************
	* 构造函数 连接数据库
	* 选择数据表
	*/

	public function __construct()
	{	
		// 数据库连接
		$this->conn = @mysqli_connect($this->host, $this->user, $this->pass);
		if (!$this->conn) {
			die('连接数据库失败!');
		}

		// 选择数据库
		if (!@mysqli_select_db($this->conn, $this->db)) {
			die('选择数据库失败');
		};
	}

	/********************************************
	* 析构函数
	* 关闭数据库
	*/

	public function __destruct()
	{
		@mysqli_close($this->conn);
	}

	/********************************************
	* 执行SQL语句
	* 
	* @param  string $str
	* @return object
	*/

	public function query($str)
	{
		$result = @mysqli_query($this->conn, $str);
		return $result;
	}

	/********************************************
	* 查询select数据
	*
	* @param string $table
	* @param string $where
	* @param string $field
	* @result array
	*/

	public function select($table, $where='', $field='*')
	{
		if (empty($where)) {
			$query = "SELECT $field FROM $table";
		} else {
			$query = "SELECT $field FROM $table WHERE $where";
		}
		$result = $this->query($query);

		$i = 0;
		while ($row = @mysqli_fetch_array($result)) {
			$data[$i++] = $row;
		}
		if (empty($data))
			return [];
		else
			return $data;
	}

	/********************************************
	* 判断账号密码是否正确
	* @param array $post
	* @return array
	*/

	public function isSuccess($post)
	{	
		// $post 是获取的账号密码
		$db = $this->select('qqx_console', 'user="'.$post['user'].'"');
		$pass = md5($post['pass'].$db[0]['create_time']);
		if ( $post['user'] == $db[0]['user']
			&& $pass == $db[0]['pass'] ) {
			$result['code'] = 0;
			$result['msg']  = '登录成功';
			$result['token'] = md5($post['user'].$post['pass']);
			return $result;
		} else {
			$result['code'] = -1;
			$result['msg']  = '账号或密码错误';
			return $result;
		}
	}
}